# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql

class WangyiproPipeline:

    def open_spider(self, spider):
        print('开始爬虫...')
        self.fp = open('./qiubai.txt','w',encoding='utf-8')

    # 专门用来处理item类型的对象
    # 该方法可以接收爬虫文件提交过来的对象
    # 该方法每接收一个item就会被调用一次
    def process_item(self, item, spider):

        title = item['title']

        self.fp.write(title+'\n')
        return item # return 就会传递给下一个执行的管道类

    def close_spider(self, spider):
        print('结束爬虫...')
        self.fp.close()

# 管道文件中一个管道类对应将一组数据存储到一个平台或一个载体中
class MysqlPipeline():
    conn = None
    cursor = None
    def open_spider(self, spider):
        self.conn = pymysql.connect(host='192.168.100.229', port=3306, user='root', password='root%123', db='test',charset='utf8')
    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            sql = ('insert into test.wangyi(title) values(%s)')
            values = (item['title'])
            self.cursor.execute(sql,values)
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        return item # return 就会传递给下一个执行的管道类,虽然没有还是应该写上

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()


# 爬虫文件提交的item类型的对象最终会提交给哪一个管道类?
    # 先执行的管道类